package com.kiloai.base.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.AttributeSet;

import com.kiloai.base.R;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by david on 17/8/5.
 */

public class CustomEditText extends android.support.v7.widget.AppCompatEditText {
    public CustomEditText(Context context) {
        super(context);
    }

    boolean isSelEnd;//是否将光标移到最后

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomEditText);
        isSelEnd = typedArray.getBoolean(R.styleable.CustomEditText_selEnd, false);
        List<InputFilter> filterList = new ArrayList<>();
        if (typedArray.getBoolean(R.styleable.CustomEditText_notSpace, false)) {//不允许输入空格
            filterList.add(new InputFilter() {
                @Override
                public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                    if (source.equals(" ")) return "";
                    else return null;
                }
            });
        }
        int maxLength = typedArray.getInteger(R.styleable.CustomEditText_maxlength, -1);//-1为不限制输入长度
        if (maxLength != -1) {
            filterList.add(new InputFilter.LengthFilter(maxLength));
        }
        if (filterList.size() > 0) {
            InputFilter[] filters = new InputFilter[filterList.size()];
            filters = filterList.toArray(filters);
            this.setFilters(filters);
        }
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onSelectionChanged(int selStart, int selEnd) {
        super.onSelectionChanged(selStart, selEnd);
        if (isSelEnd) {
            this.setSelection(getText().toString().length());
        }
    }
}
